package com.sixdog.regulate.utils;

import javax.xml.crypto.Data;
import java.util.Calendar;
import java.util.Date;

public class TimeUtils {
    //生成一个日期时间对象
    public static Date getTime(int year, int month, int date, int hour, int min, int sec){
        Calendar c = Calendar.getInstance();
        c.set(year,month-1,date,hour,min,sec);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }
    public static Date getTime(int year,int month,int date){
        return getTime(year, month, date,0,0,0);
    }

    //通过睡眠实现定时矫正
    public static void sleepCorrectTiming(Date date,long advanceMillisecond){
        //得到日期时间的毫秒时间戳
        long time = date.getTime();
        try {
            //算出还有多久到指定时间,然后睡眠
            long l = time - System.currentTimeMillis() - advanceMillisecond;
            System.out.println("线程睡眠时长："+l);
            Thread.sleep(l);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //通过date生成cron表达式,可传提前秒数使cron比Date提前
    public static String getCron(Date dateTime,int advanceSec){
        Date date1 = new Date(dateTime.getTime() - (advanceSec * 1000));
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date1);

        int year = calendar.get(Calendar.YEAR);//获取年份
        int month = calendar.get(Calendar.MONTH)+1;//获取月份
        int date = calendar.get(Calendar.DATE);//获取日
        int hour = calendar.get(Calendar.HOUR_OF_DAY);//时（24小时制）
        int minute = calendar.get(Calendar.MINUTE);//分
        int second = calendar.get(Calendar.SECOND);//秒
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);//一周的第几天

        return ""+second+" "+minute+" "+hour+" "+date+" "+month+" "+"*";
    }

}
